﻿using BBICMS.Model.Security;
using Elmah;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;
using WebMatrix.WebData;

namespace BBICMS.WebUI
{
    // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明，
    // 请访问 http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            //webAPI
           // GlobalConfiguration.Configure(WebApiConfig.Register);

            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            

            BundleConfig.RegisterBundles(BundleTable.Bundles);
            //AuthConfig.RegisterAuth();

            CustomGlobalConfig.Customize(GlobalConfiguration.Configuration);

            //json 序列化
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;


           // Bootstrapper.Initialise();
            Bootstrapper.Run();





        }

        protected void Application_BeginRequest()
        {
            
        }

        protected void Application_EndRequest()
        {
           
        }
        protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
        {
            HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
            if (authCookie != null)
            {

                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

                CustomPrincipalSerializeModel serializeModel = JsonConvert.DeserializeObject<CustomPrincipalSerializeModel>(authTicket.UserData);
                CustomPrincipal newUser = new CustomPrincipal(authTicket.Name);
                newUser.UserId = serializeModel.UserId;
                newUser.RealName = serializeModel.RealName;
                newUser.Roles = serializeModel.Roles;
                newUser.Avatar = serializeModel.Avatar;
                //newUser.Menus = serializeModel.Menus;

                HttpContext.Current.User = newUser;
            }

        }

        private void ErrorLog_Filtering(object sender, ExceptionFilterEventArgs e)
        {
            if (e.Exception is System.Threading.ThreadAbortException)
            {
                e.Dismiss();
            }
        }
    }
}